from django.db.models import Q
from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from .models import *
import jwt,requests,re
from p6shixun.settings import SECRET_KEY  # 导入 setting中的 秘钥
from rest_framework.response import Response
from django.utils.decorators import method_decorator
from p6shixun.settings import *
from urllib.parse import urlencode
from PIL import Image,ImageDraw,ImageFont
from io import BytesIO
import random
import string
from django.core.cache import cache
from django.core.mail import send_mail
from celery_demo.mytasks import sendMail
# 登录接口

def mytest(func):
    def inner(request):
        token = request.META.get("HTTP_AUTHORIZATION")
        try:
            data = jwt.decode(token,SECRET_KEY,algorithms=["HS256"])
            uid = data.get('uid')
        except Exception as e:
            print(e)
            uid = None
        request.COOKIES['uid']=uid
        return func(request)
    return inner


def make_image_code(request):
    uuid = request.GET.get("uuid")
    print("uuid:",uuid)

    image = Image.new('RGB', (120, 30), 'lightblue')
    # 创建图形字体
    draw = ImageDraw.Draw(image)

    font = ImageFont.truetype("simsun.ttc", size=20)
    # 随机生成4为字符串
    words = random.sample(string.ascii_letters + string.digits, 4)
    words = "".join(words)
    cache.set(uuid,words,15)

    draw.text((10, 5), words, fill="black", font=font),

    fp = BytesIO()
    image.save(fp, 'png')
    # 从字节流获取数据
    data = fp.getvalue()
    return HttpResponse(data, content_type="image/png")


class LoginView(APIView):
    def post(self,request):
        username = request.data.get("username") # 也可以用data
        password = request.data.get("password")
        # 进行验证 是否正确是否存在
        user = UserModel.objects.filter(Q(username=username) | Q(email=username)).first()
        if user and user.password == password:
            info = {
                "uid": user.id,
                "username": user.username
            }
            # 验证通过，生成jwt令牌
            token = jwt.encode(info, SECRET_KEY)
            return Response({"msg": "登录成功", "token": token})
        else:
            # 验证失败
            return Response({"msg": "登录失败"}, status=401)


@method_decorator(mytest,name='dispatch')
class TestView(APIView): # 校验令牌
    def get(self, request):
        # token = request.META.get("HTTP_AUTHORIZATION")  在请求头中获取token
        uid = request.COOKIES.get("uid")
        if uid:
            return Response({"msg": "令牌有效"})
        else:

            return Response({"msg": "令牌无效"}, status=401)

    def post(self, request):
        uid = request.COOKIES.get("uid")
        if uid:
            return Response({"msg": "令牌有效"})
        else:
            return Response({"msg": "令牌无效"}, status=401)


class WeiboView(APIView):
    def get(self,request):
        code = request.query_params.get("code")
        print(code)
        data = {
            "client_id": str(App_Key),
            "client_secret":App_Secret,
            "grant_type":"authorization_code",
            "code": code,
            "redirect_uri": WEIBO_URL
        }
        r = requests.post('https://api.weibo.com/oauth2/access_token',data)
        print(r.json())
        uid = r.json().get("uid")
        if not uid:
            return Response({"msg":"微博登录失败"},status=401)
        access_token = r.json()["access_token"]
        print("uid",uid)
        print("access_token",access_token)

        open_user = OpenUser.objects.filter(uid=uid).first()
        if not open_user:
            OpenUser.objects.create(uid=uid,type=1)
            return Response({"msg":"登录成功","code":202,"uid":uid})
        return Response({"msg":"登录成功","code":200})

    def post(self,request):
        username = request.data.get("username")
        password = request.data.get("password")
        uid = request.data.get("uid")
        print(uid)
        # 验证用户名和密码
        user=UserModel.objects.filter(username=username,password=password).first()
        if not user:
            return Response({"msg":"账号不存在","code":400})
        OpenUser.objects.filter(uid=uid).update(user_id=user.id)
        return Response({"msg":"绑定成功","code":200})


class Register(APIView):
    def post(self,request):
        username = request.data.get("username")
        password = request.data.get("password")
        email = request.data.get("email")

        uuid = request.data.get("uuid")
        code = request.data.get("code")

        old_code = cache.get(uuid)
        print("code:", code)
        print("old_code:", old_code)

        if code.lower() != str(old_code).lower():
            return Response({"msg":"验证码错误"})
        user=UserModel.objects.create(username=username,password=password,email=email)
        # 发送邮件的任务 异步
        sendMail.delay(email,user.id)
        return Response({"msg":"注册成功","code":200})


def active_user(request):
    uid = request.GET.get("uid")
    UserModel.objects.filter(id=uid).update(status=2)
    return HttpResponse("恭喜你，激活成功，可以跳转到登录页<a href='http://127.0.0.1:8080/login'>请点击跳转</a>")


class Check(APIView):
    def post(self,request):
        username = request.data.get("username")
        # 后端用户名正则验证
        if not re.match(r"^\w{2,8}$",username):
            return Response({"msg":"用户名长度必须要2-8位","code":400})
        user = UserModel.objects.filter(username=username)
        if user:
            return Response({"msg":"已经存在"})
        else:
            return Response({"msg": "√"})





